//! 中间件模块
//! 提供统一的中间件接口和实现

use crate::auth::{AuthPolicy, AuthContext, AuthRequest, AuthResult};
use std::sync::Arc;

/// 中间件特征
pub trait Middleware: Send + Sync {
    type Request;
    type Response;
    type Error;

    fn call(
        &self,
        req: Self::Request,
        next: Box<dyn Fn(Self::Request) -> Result<Self::Response, Self::Error> + Send + Sync>,
    ) -> Result<Self::Response, Self::Error>;
}

/// 中间件链
pub struct MiddlewareChain {
    middlewares: Vec<Arc<dyn Middleware<Request = AuthRequest, Response = AuthContext, Error = crate::auth::AuthError>>>,
}

impl MiddlewareChain {
    pub fn new() -> Self {
        Self {
            middlewares: Vec::new(),
        }
    }

    pub fn add_middleware(mut self, middleware: Arc<dyn Middleware<Request = AuthRequest, Response = AuthContext, Error = crate::auth::AuthError>>) -> Self {
        self.middlewares.push(middleware);
        self
    }

    pub fn execute(&self, request: AuthRequest) -> AuthResult<AuthContext> {
        // 简化实现，只执行第一个中间件
        if let Some(middleware) = self.middlewares.first() {
            middleware.call(request, Box::new(|_| Ok(AuthContext::new("default".to_string()))))
        } else {
            Ok(AuthContext::new("anonymous".to_string()))
        }
    }
}

impl Default for MiddlewareChain {
    fn default() -> Self {
        Self::new()
    }
}

/// 认证中间件
pub struct AuthMiddleware {
    auth_policy: Arc<dyn AuthPolicy>,
}

impl AuthMiddleware {
    pub fn new(auth_policy: Arc<dyn AuthPolicy>) -> Self {
        Self { auth_policy }
    }
}

impl Middleware for AuthMiddleware {
    type Request = AuthRequest;
    type Response = AuthContext;
    type Error = crate::auth::AuthError;

    fn call(
        &self,
        req: Self::Request,
        _next: Box<dyn Fn(Self::Request) -> Result<Self::Response, Self::Error> + Send + Sync>,
    ) -> Result<Self::Response, Self::Error> {
        self.auth_policy.authenticate(&req)
    }
}

/// 日志中间件
pub struct LoggingMiddleware;

impl Middleware for LoggingMiddleware {
    type Request = AuthRequest;
    type Response = AuthContext;
    type Error = crate::auth::AuthError;

    fn call(
        &self,
        req: Self::Request,
        next: Box<dyn Fn(Self::Request) -> Result<Self::Response, Self::Error> + Send + Sync>,
    ) -> Result<Self::Response, Self::Error> {
        println!("Processing request: {:?}", req.headers);
        
        // 调用下一个中间件
        let result = next(req);
        
        match &result {
            Ok(context) => println!("Request authenticated for user: {}", context.user_id),
            Err(e) => println!("Authentication failed: {}", e),
        }
        
        result
    }
}

/// 限流中间件
pub struct RateLimitMiddleware {
    max_requests: u32,
    window_seconds: u64,
}

impl RateLimitMiddleware {
    pub fn new(max_requests: u32, window_seconds: u64) -> Self {
        Self {
            max_requests,
            window_seconds,
        }
    }
}

impl Middleware for RateLimitMiddleware {
    type Request = AuthRequest;
    type Response = AuthContext;
    type Error = crate::auth::AuthError;

    fn call(
        &self,
        req: Self::Request,
        next: Box<dyn Fn(Self::Request) -> Result<Self::Response, Self::Error> + Send + Sync>,
    ) -> Result<Self::Response, Self::Error> {
        // 简化的限流逻辑
        println!("Rate limiting check: max {} requests per {} seconds", self.max_requests, self.window_seconds);
        
        next(req)
    }
}

/// CORS中间件
pub struct CorsMiddleware {
    allowed_origins: Vec<String>,
    _allowed_methods: Vec<String>,
    _allowed_headers: Vec<String>,
}

impl CorsMiddleware {
    pub fn new() -> Self {
        Self {
            allowed_origins: vec!["*".to_string()],
            _allowed_methods: vec!["GET".to_string(), "POST".to_string(), "PUT".to_string(), "DELETE".to_string()],
            _allowed_headers: vec!["Content-Type".to_string(), "Authorization".to_string()],
        }
    }

    pub fn with_origins(mut self, origins: Vec<&str>) -> Self {
        self.allowed_origins = origins.iter().map(|s| s.to_string()).collect();
        self
    }
}

impl Default for CorsMiddleware {
    fn default() -> Self {
        Self::new()
    }
}

impl Middleware for CorsMiddleware {
    type Request = AuthRequest;
    type Response = AuthContext;
    type Error = crate::auth::AuthError;

    fn call(
        &self,
        req: Self::Request,
        next: Box<dyn Fn(Self::Request) -> Result<Self::Response, Self::Error> + Send + Sync>,
    ) -> Result<Self::Response, Self::Error> {
        println!("CORS check: allowed origins: {:?}", self.allowed_origins);
        
        next(req)
    }
}